package com.ruoyi.project.system.service.impl;

import com.ruoyi.project.system.domain.MedicineSimple;
import com.ruoyi.project.system.domain.dto.MedicineItemDTO;
import com.ruoyi.project.system.domain.dto.ResWithMedicinesDTO;
import com.ruoyi.project.system.mapper.ResMedMapper;
import com.ruoyi.project.system.service.IResMedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ResMedServiceImpl implements IResMedService {

    private static final Logger log = LoggerFactory.getLogger(ResMedServiceImpl.class);

    @Autowired
    private ResMedMapper resMedMapper;
    
    // 注入MedicineMapper以更新药品库存
    @Autowired
    private com.ruoyi.project.system.mapper.MedicineMapper medicineMapper;

    @Override
    public List<ResWithMedicinesDTO> getResWithMedicines() {
        log.info("开始查询resolve=1的预约记录及关联药品");
        try {
            // 第一步：查询所有resolve=1的预约记录
            List<ResWithMedicinesDTO> resList = resMedMapper.selectResByResolveOne();
            if (resList == null || resList.isEmpty()) {
                log.info("未查询到resolve=1的预约记录");
                return resList;
            }

            // 第二步：遍历每个预约记录，关联查询对应的药品信息
            for (ResWithMedicinesDTO res : resList) {
                String resId = res.getResId();
                // 通过res_id查询药品列表
                List<MedicineItemDTO> medList = resMedMapper.selectMedicinesByResId(resId);
                // 给当前预约记录设置药品列表
                res.setMedicineList(medList);
            }
            
            // 过滤掉药品清单为空的预约记录
            List<ResWithMedicinesDTO> filteredResList = resList.stream()
                    .filter(res -> res.getMedicineList() != null && !res.getMedicineList().isEmpty())
                    .collect(Collectors.toList());

            log.info("查询完成，共找到{}条符合条件的预约记录", filteredResList.size());
            return filteredResList;
        } catch (Exception e) {
            log.error("查询预约记录及关联药品失败", e);
            throw new RuntimeException("查询失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public boolean processMedicineDistribution(String resId) {
        log.info("开始处理药品下发，预约号: {}", resId);
        try {
            // 通过res_id查询药品列表
            List<MedicineItemDTO> medList = resMedMapper.selectMedicinesByResId(resId);
            
            if (medList == null || medList.isEmpty()) {
                log.warn("预约号 {} 没有找到相关药品记录", resId);
                return false;
            }
            
            // 遍历药品列表，减少对应药品的库存
            for (MedicineItemDTO medicine : medList) {
                Long medId = medicine.getMedId();
                Integer quantity = medicine.getNumber();
                
                if (medId == null || quantity == null || quantity <= 0) {
                    log.warn("药品信息不完整或数量无效: medId={}, quantity={}", medId, quantity);
                    continue;
                }
                
                // 查询当前药品信息
                MedicineSimple medicineInfo = medicineMapper.selectMedicineById(medId);
                        
                if (medicineInfo == null) {
                    log.warn("未找到ID为 {} 的药品信息", medId);
                    continue;
                }
                
                // 检查库存是否充足
                int currentStock = medicineInfo.getStock();
                if (currentStock < quantity) {
                    log.error("药品 {} 库存不足，当前库存: {}, 需要: {}", medicineInfo.getName(), currentStock, quantity);
                    throw new RuntimeException("药品 " + medicineInfo.getName() + " 库存不足");
                }
                
                // 更新库存（减去发放数量）
                MedicineSimple updatedMedicine = new MedicineSimple();
                updatedMedicine.setId(medId);
                updatedMedicine.setStock(quantity); // 传递要减少的数量
                
                int rowsAffected = medicineMapper.updateMedicineStock(updatedMedicine);
                if (rowsAffected > 0) {
                    log.info("成功更新药品 {} 的库存: {} -> {}", 
                            medicineInfo.getName(), currentStock, currentStock - quantity);
                } else {
                    log.warn("更新药品 {} 的库存失败，可能是库存不足", medicineInfo.getName());
                    throw new RuntimeException("药品 " + medicineInfo.getName() + " 库存不足");
                }
            }
            
            // 更新预约记录的状态为5（表示药品已发放）
            int updatedRows = resMedMapper.updateResResolveStatus(resId, 5);
            if (updatedRows > 0) {
                log.info("成功更新预约 {} 的状态为5", resId);
            } else {
                log.warn("更新预约 {} 的状态失败", resId);
            }
            
            log.info("药品下发处理完成，预约号: {}", resId);
            return true;
        } catch (Exception e) {
            log.error("处理药品下发失败，预约号: " + resId, e);
            throw new RuntimeException("处理药品下发失败: " + e.getMessage());
        }
    }
}